package service

import (
	"douyin/controller/api/response"
	"douyin/dao"
	"douyin/errno"
	"douyin/model"
	"sync"
)

type commentService struct{}

var (
	commentServiceInstance *commentService
	commentServiceOnce     sync.Once
)

// NewComment 单例模式创建 CommentServiceInstance
func NewComment() *commentService {
	commentServiceOnce.Do(func() {
		commentServiceInstance = &commentService{}
	})
	return commentServiceInstance
}

// Add 新增评论操作 c 里面包含了userID、videoID、content三项
// 其他的信息，如创建时间由数据库自动生成
// 成功返回 response.OK
// 失败返回对应的错误信息
func (*commentService) Add(c model.Comment) response.Status {
	if err := dao.NewComment().Add(&c); err != nil {
		return response.Status{
			Code:    errno.ErrCommentAddFail.Code,
			Message: errno.ErrCommentAddFail.Message,
		}
	}

	//dao.NewComment().IncreaseCommentCountByCache(c.VideoID, 1) 缓存暂时不用
	if err := dao.NewVideo().AddComment(c.VideoID, 1); err != nil {
		return response.Status{
			Code:    errno.ErrCommentAddFail.Code,
			Message: errno.ErrCommentAddFail.Message,
		}
	}

	return response.OK
}

// Del 删除评论操作，只需要提供评论id即可
// 成功返回 response.OK
// 失败返回对应的错误信息
func (*commentService) Del(id int64) response.Status {
	if err := dao.NewComment().Delete(id); err != nil {
		return response.Status{
			Code:    errno.ErrCommentDelFail.Code,
			Message: errno.ErrCommentDelFail.Message,
		}
	}
	//dao.NewComment().DecreaseCommentCountByCache(id, 1)  缓存暂时不用
	if err := dao.NewVideo().SubComment(id, 1); err != nil {
		return response.Status{
			Code:    errno.ErrCommentDelFail.Code,
			Message: errno.ErrCommentDelFail.Message,
		}
	}

	return response.OK
}

// List 返回某视频的所有的评论
func (*commentService) List(videoID int64) response.CommentList {
	handleErr := func(errType *errno.Errno) response.CommentList {
		return response.CommentList{Status: response.Status{
			Code:    errType.Code,
			Message: errType.Message,
		}}
	}
	comments, err := dao.NewComment().List(videoID)
	if err != nil {
		return handleErr(errno.ErrQueryCommentListFail)
	}
	c := newCommentAPIList(comments)

	return response.CommentList{Status: response.OK, CommentLists: c}
}

// 构造 commentList
func newCommentAPIList(cc []model.Comment) []model.CommentAPI {
	var c []model.CommentAPI

	for _, i := range cc {
		resp, _ := NewUser().Info(i.UserID)
		c = append(c, model.CommentAPI{
			ID:       i.ID,
			User:     resp.User,
			Content:  i.Content,
			CreateAt: i.CreateAt.Format("01-02 15:04:05"),
		})
	}
	return c
}
